<template>
  <div class="add">
    <div class="buttons">
      <el-button
        type="primary"
        icon="el-icon-back"
        size="small"
        @click="jump(-1)">返回</el-button>
    </div>
    <template>
      <el-row>
        <el-col :span="24">
          <el-form label-width="80px" :model="form.address_info">
            <el-form-item label="区域">
              <el-select placeholder="请选择省份" @change="getCity" v-model="form.address_info.province.id">
                <template v-for="(item,idx) in province">
                  <el-option :label="item.name" :value="item.id" :key="'province' + idx"></el-option>
                </template>
              </el-select>
              <el-select placeholder="请选择城市" v-if="city.length > 0" @change="getCounty" v-model="form.address_info.city.id">
                <template v-for="(item,idx) in city">
                  <el-option :label="item.name" :value="item.id" :key="'county' + idx"></el-option>
                </template>
              </el-select>
              <el-select placeholder="请选择区/县" v-if="county.length > 0" v-model="form.address_info.county.id">
                <template v-for="(item,idx) in county">
                  <el-option :label="item.name" :value="item.id" :key="'city' + idx"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <template v-for="(item, idx) in form.collection_point">
          <el-col :span="24" :key="'collection_point' + idx">
            <el-form :inline="true" label-width="80px">
              <el-form-item label="上车点">
                <el-input v-model.trim="item.title"></el-input>
              </el-form-item>
              <el-form-item label="地址">
                <el-input :value="item.address" disabled></el-input>
              </el-form-item>
              <el-form-item label="经纬度">
                <el-input :value="(item.lng && item.lat) ? item.lng+','+item.lat : ''" disabled></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getPointByMap(idx)">地图选点</el-button>
              </el-form-item>
              <el-form-item v-if="idx !== 0">
                <el-button type="danger" @click="deleteCollectionPoint(idx)">删除</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </template>
        <el-col :span="24">
          <el-form label-width="80px">
            <el-form-item>
              <el-button type="primary" @click="submit">保存</el-button>
              <el-button type="default" @click="createCollectionPoint">新增一组</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </template>
    <el-dialog ref="amap" top="2rem" title="地图选点" :visible.sync="showMapStatus">
      <div class="search">
        <el-input v-model="marker.searchAddress" placeholder="请输入详细地址" class="input-with-select">
          <el-button @click="getLocationByAddress" slot="append" type="success" icon="el-icon-search"></el-button>
        </el-input>
      </div>
      <el-amap
        :events="events"
        :zoom="zoom"
        ref="map"
        :center="initLngLat"
        :amap-manager="amapManager"
        :plugin="plugin"
        class="amap"
        vid="amapDemo">
        <el-amap-marker
          :position="marker.position"
          vid="index"></el-amap-marker>
      </el-amap>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showMapStatus = false">取 消</el-button>
        <el-button type="primary" @click="getAddress">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {amapManager} from 'vue-amap'
  export default {
    data () {
      return {
        initLngLat: [],
        amapManager,
        zoom: 12,
        events: {
          init: (o) => {
            // console.log(o)
          },
          click: (e) => {
            this.marker.position = [e.lnglat.lng, e.lnglat.lat]
            this.getAddressByLocation()
          }
        },
        plugin: ['ToolBar'],
        showMapStatus: false,
        province: [],
        city: [],
        county: [],
        form: {
          address_info: {
            province: {
              id: '',
              name: '',
              code: ''
            },
            city: {
              id: '',
              name: '',
              code: ''
            },
            county: {
              id: '',
              name: '',
              code: ''
            }
          },
          collection_point: [{
            title: '',
            lng: '',
            lat: '',
            address: ''
          }]
        },
        marker: {
          position: [],
          searchAddress: ''
        },
        mapIndex: null
      }
    },
    watch: {
      'form.address_info.province.id' (id) {
        if (id) {
          this.province.map(item => {
            if (item.id === id) {
              this.form.address_info.province.name = item.name
              this.form.address_info.province.code = item.area_code
              this.form.address_info.province.id = item.id
              // 重置
              this.form.address_info.city.name = ''
              this.form.address_info.city.code = ''
              this.form.address_info.city.id = ''
              this.form.address_info.county.name = ''
              this.form.address_info.county.id = ''
              this.form.address_info.county.code = ''

              this.initLngLat = []
              this.marker.position = []
            }
          })
        } else {
          this.form.address_info.province.name = ''
          this.form.address_info.province.code = ''
          this.form.address_info.province.id = ''
        }
      },
      'form.address_info.city.id' (id) {
        if (id) {
          this.city.map(item => {
            if (item.id === id) {
              this.form.address_info.city.name = item.name
              this.form.address_info.city.code = item.area_code
              this.form.address_info.city.id = item.id
              this.initLngLat = [item.lng, item.lat]
              this.marker.position = [item.lng, item.lat]
              // 重置
              this.form.address_info.county.name = ''
              this.form.address_info.county.id = ''
              this.form.address_info.county.code = ''
            }
          })
        } else {
          this.form.address_info.city.name = ''
          this.form.address_info.city.code = ''
          this.form.address_info.city.id = ''
        }
      },
      'form.address_info.county.id' (id) {
        if (id) {
          this.county.map(item => {
            if (item.id === id) {
              this.form.address_info.county.name = item.name
              this.form.address_info.county.id = item.id
              this.form.address_info.county.code = item.area_code
              this.initLngLat = [item.lng, item.lat]
              this.marker.position = [item.lng, item.lat]
            }
          })
        } else {
          this.form.address_info.county.name = ''
          this.form.address_info.county.id = ''
          this.form.address_info.county.code = ''
        }
      },
      showMapStatus (val) {
        this.marker.searchAddress = this.form.address_info.province.name + this.form.address_info.city.name + this.form.address_info.county.name
        this.marker.position = this.initLngLat
      }
    },
    methods: {
      /**
       *  地图选点
       */
      getPointByMap (idx) {
        console.log(idx)
        console.log(this.initLngLat)
        if (this.initLngLat.length !== 2) {
          this.toast('请先选择区域', 'warning')
          return false
        }
        this.showMapStatus = true
        this.mapIndex = idx
      },
      /**
       * 经纬度解析
       */
      getLocationByAddress () {
        if (!this.marker.searchAddress) {
          this.toast('请输入详细地址!', 'warning')
          return false
        }
        this.showLoading()
        this
          .$api
          .map
          .getLocationByAddress(this.marker.searchAddress, this.form.address_info.city.name)
          .then(r => {
            if (r.length < 1) {
              this.toast('没有搜索到相关信息,你可以切换城市试试...', 'warning')
              return false
            }
            this.initLngLat = r[0].location.split(',')
            this.marker.searchAddress = r[0].formatted_address
            this.marker.position = r[0].location.split(',')
            // r.map(item => {
            //   this.markers.push({
            //     searchAddress: item.formatted_address,
            //     position: item.location.split(','),
            //     events: {
            //       click: (e) => {
            //         console.log(e)
            //       }
            //     }
            //   })
            // })
          })
      },
      /**
       * 地址逆解析
       */
      getAddressByLocation () {
        this.showLoading()
        this
          .$api
          .map
          .getAddressByLocation(this.marker.position.join(','))
          .then(r => {
            this.marker.searchAddress = r.formatted_address
          })
      },
      /**
       *  删除集合点
       */
      deleteCollectionPoint (idx) {
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.collection_point = this.form.collection_point.filter((_, _idx) => {
            return Number(idx) !== Number(_idx)
          })
        }).catch(() => {})
      },
      /**
       * 新增一个集合点
       */
      createCollectionPoint () {
        this.form.collection_point.push({
          title: '',
          lng: '',
          lat: '',
          address: ''
        })
      },
      /**
       * @purpose 获取所有省份
       */
      getProvince () {
        this
          .$api
          .area
          .item()
          .then(r => {
            this.province = r
          })
      },
      /**
       * @purpose 获取城市
       * @param e
       * @returns {boolean}
       */
      getCity (e) {
        this
          .$api
          .area
          .item(e)
          .then(r => {
            this.city = r
            this.county = []
          })
      },
      /**
       * 区/县
       */
      getCounty (e) {
        this
          .$api
          .area
          .item(e)
          .then(r => {
            this.county = r
          })
      },
      /**
       * @purpose 获取地址
       */
      getAddress () {
        if (this.marker.searchAddress === '') {
          this.toast('请选择地址！', 'warning')
        } else {
          this.form.collection_point = this.form.collection_point.map((item, idx) => {
            if (idx === Number(this.mapIndex)) {
              item.title = this.marker.searchAddress
              item.address = this.marker.searchAddress
              item.lng = this.marker.position[0]
              item.lat = this.marker.position[1]
            }
            return item
          })
          console.log(this.form.collection_point)
          this.showMapStatus = false
        }
      },
      /**
       * @purpose 提交数据
       */
      submit () {
        if (!this.form.address_info.province.id) {
          this.$message.error(this.$lang('请选择省份!'))
          return false
        }
        if (!this.form.address_info.city.id) {
          this.$message.error(this.$lang('请选择城市!'))
          return false
        }
        if (!this.form.address_info.province.id) {
          this.$message.error(this.$lang('请选择区域!'))
          return false
        }
        // if (!this.form.collection_point.title) {
        //   this.$message.error(this.$lang('请填写上车点!'))
        //   return false
        // }
        this.form.collection_point.map(item => {
          if (!item.title) {
            this.$message.error(this.$lang('请填写上车点!'))
            return false
          }
        })
        this.showLoading()
        this
          .$api
          .map
          .addCollectionPoint(this.form)
          .then(r => {
            this.$confirm('添加成功！', '提示', {
              confirmButtonText: '继续添加',
              cancelButtonText: '返回',
              type: 'success'
            }).then(() => {
              this.city = []
              this.county = []
              this.form = {
                address_info: {
                  province: {
                    id: '',
                    name: '',
                    code: ''
                  },
                  city: {
                    id: '',
                    name: '',
                    code: ''
                  },
                  county: {
                    id: '',
                    name: '',
                    code: ''
                  }
                },
                collection_point: [{
                  title: '',
                  lng: '',
                  lat: '',
                  address: ''
                }]
              }
            }).catch(() => {
              this.jump(-1)
            })
          })
      }
    },
    created () {
      this.getProvince()
    }
  }
</script>
<style lang="sass">
  .el-dialog__body
    padding: 0 20px
</style>
<style scoped lang="sass">
  .search
    width: 100%
    margin: 10px 0 20px 0
  .amap
    height: 500px
    .search-box
      position: absolute
      top: 25px
      left: 20px
    .amap-page-container
      position: relative
</style>
